package com.lineage.server.timecontroller.event;

import com.lineage.data.event.LeavesSet;
import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.serverpackets.S_PacketBoxExp;
import com.lineage.server.serverpackets.ServerBasePacket;
import com.lineage.server.thread.GeneralThreadPool;
import com.lineage.server.world.World;
import java.util.Collection;
import java.util.Iterator;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class LeavesTime extends TimerTask {
  private static final Log _log = LogFactory.getLog(LeavesTime.class);
  
  private ScheduledFuture<?> _timer;
  
  public void start() {
    int timeMillis = 60000;
    this._timer = GeneralThreadPool.get().scheduleAtFixedRate(this, 60000L, 60000L);
  }
  
  public void run() {
    try {
      Collection<L1PcInstance> all = World.get().getAllPlayers();
      if (all.isEmpty())
        return; 
      Iterator<L1PcInstance> iter = all.iterator();
      while (iter.hasNext()) {
        L1PcInstance tgpc = iter.next();
        if (check(tgpc)) {
          int time = tgpc.getlogintime1();
          tgpc.setlogintime1(time + 1);
          if (tgpc.getlogintime1() >= LeavesSet.TIME) {
            tgpc.setlogintime1(0);
            int exp = tgpc.getlogintime();
            int addexp = exp + LeavesSet.EXP;
            tgpc.setlogintime(addexp);
            if (tgpc.getlogintime() > 960000)
              tgpc.setlogintime(960000); 
            tgpc.sendPackets((ServerBasePacket)new S_PacketBoxExp(tgpc.getlogintime() / LeavesSet.EXP));
          } 
          Thread.sleep(100L);
        } 
      } 
    } catch (Exception e) {
      _log.error("殷海萨的祝福-休息系统时间轴异常重启", e);
      GeneralThreadPool.get().cancel(this._timer, false);
      LeavesTime leavesTime = new LeavesTime();
      leavesTime.start();
    } 
  }
  
  private static boolean check(L1PcInstance tgpc) {
    try {
      if (tgpc == null)
        return false; 
      if (tgpc.getOnlineStatus() == 0)
        return false; 
      if (tgpc.getNetConnection() == null)
        return false; 
      if (tgpc.isDead())
        return false; 
      if (!tgpc.isSafetyZone())
        return false; 
      if (tgpc.isTeleport())
        return false; 
      if (tgpc.getlogintime() >= LeavesSet.MAXEXP)
        return false; 
      if (tgpc.getHpRegenState() == 1)
        return false; 
      if (tgpc.getLevel() < LeavesSet.MIN_LEVEL)
        return false; 
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
      return false;
    } 
    return true;
  }
}
